/**
 * 面试列表页
 */
import React from 'react';
import moment from 'moment';
import { router, withRouter } from 'umi';
import { Input, Button, Form, Icon, DatePicker } from 'antd';
import { isEqual } from 'lodash';
import { useRequest } from '@/hooks';
import { Pagination } from '@/components';

import styles from './List.less';
import { InterviewCommonTable } from '../containers';
import { CustomSearch } from '../components';
import { queryInterviewList } from '../service';

function InterviewList({ form, location, recruitCode, onDataExchange, isPrincipal, isLauncher }) {
    const { query } = location;
    const { getFieldDecorator } = form;
    const {
        startInterviewStartTime,
        endInterviewStartTime,
        talentName,
        name,
        talentSex,
        interviewerEmployeeName,
        orderByField
    } = query;
    const sortOrders = React.useMemo(() => {
        if (!orderByField) {
            return {};
        }
        return orderByField.split(',').reduce((pre, item) => {
            const [key, value] = item.split('|');
            return { ...pre, [key]: `${value}end` };
        }, {});
    }, [orderByField]);
    // 需转换成数字
    let { pageNo = 1, pageSize = 10, interviewStatus } = query;
    const { interviewRoundName } = query;
    const toNumber = val => (val ? Number(val) : undefined);
    pageNo = toNumber(pageNo);
    pageSize = toNumber(pageSize);
    const interviewRound = toNumber(interviewRoundName);
    interviewStatus = toNumber(interviewStatus);
    const sourceCondition = {
        pageNo,
        pageSize,
        name,
        recruitCode,
        startInterviewStartTime,
        endInterviewStartTime,
        talentName,
        talentSex,
        interviewRound,
        interviewerEmployeeName,
        interviewStatus,
        orderByField
    };
    // 查询条件
    const condition = React.useMemo(
        () =>
            Object.keys(sourceCondition).reduce((ret, key) => {
                const item = sourceCondition[key];
                if (!item && item !== 0) {
                    return ret;
                }
                return { ...ret, [key]: item };
            }, {}),
        [...Object.values(sourceCondition)]
    );

    // 设置条件
    const setCondition = n => {
        history.push({ query: { ...query, ...n } });
    };
    // 查询
    const { data, loading, run } = useRequest(() => queryInterviewList(condition), {
        refreshDeps: [condition]
    });
    // 无刷新逻辑
    const [dataSource, setDataSource] = React.useState([]);
    React.useEffect(() => {
        setDataSource(data?.data?.rows || []);
    }, [data]);

    // 高级搜索展开标识
    const [advanceFold, setAdvanceFold] = React.useState(true);

    /**
     * 获取表单数据
     */
    const getFormCondition = React.useCallback(async () => {
        let values = {};
        try {
            values = await form.validateFields();
            const { dateRange = [], ...rest } = values;
            let startTime;
            let endTime;
            if (dateRange.length) {
                startTime = moment(dateRange[0]).format('YYYY-MM-DD 00:00:00');
                endTime = moment(dateRange[1]).format('YYYY-MM-DD 23:59:59');
            }
            values = { startInterviewStartTime: startTime, endInterviewStartTime: endTime, ...rest };
        } catch (error) {
            console.log(error);
        }
        return values;
    }, []);
    // 刷新
    const handleRefresh = React.useCallback(() => {
        run();
        onDataExchange();
    }, [run]);

    // 表格变化
    const handleTableChange = async (pagination, filters, sorter) => {
        const values = await getFormCondition();
        const con = Object.keys(filters).reduce(
            (ret, key) => {
                const item = filters[key];
                return { ...ret, [key]: item.length > 0 ? item[0] : '' };
            },
            { pageNo: 1 }
        );
        let orderBy = '';
        if (sorter && sorter.field && sorter.order) {
            orderBy = `${sorter.field}|${sorter.order.replace('end', '')}`;
        }
        setCondition({ orderByField: orderBy, ...con, ...values });
    };
    // 跳转明细
    const handleJumpDetail = React.useCallback(async (candidateId, resumeId) => {
        history.push({
            pathname: '/office/personnelManagement/recruitment/resume/detail',
            query: { id: resumeId, candidateId, activeKey: 'INTERVIEW' }
        });
    }, []);
    // 点击查询
    const handleSearch = async val => {
        const values = await getFormCondition();
        const newPart = { ...values, ...val, pageNo: 1 };
        if (isEqual(query, { ...query, ...newPart })) {
            run();
        } else {
            setCondition(newPart);
        }
    };
    // 高阶条件
    const renderAdvanceCon = () => {
        if (advanceFold) {
            return '';
        }
        return (
            <div className={styles.advanceCon}>
                <Form.Item label="姓名">
                    {getFieldDecorator('talentName', {
                        initialValue: talentName
                    })(<Input placeholder="请输入" allowClear style={{ width: 190 }} />)}
                </Form.Item>

                <Form.Item label="面试官">
                    {getFieldDecorator('interviewerEmployeeName', { initialValue: interviewerEmployeeName })(
                        <Input placeholder="请输入" allowClear style={{ width: 190 }} />
                    )}
                </Form.Item>
                <Form.Item label="面试时间">
                    {getFieldDecorator('dateRange', {
                        initialValue:
                            startInterviewStartTime && endInterviewStartTime
                                ? [moment(startInterviewStartTime), moment(endInterviewStartTime)]
                                : undefined
                    })(
                        <DatePicker.RangePicker
                            ranges={{
                                本周: [moment().startOf('week'), moment().endOf('week')],
                                本月: [moment().startOf('month'), moment().endOf('month')],
                                本季度: [moment().startOf('quarter'), moment().endOf('quarter')]
                            }}
                        />
                    )}
                </Form.Item>
            </div>
        );
    };
    // 表格
    const renderTable = () => (
        <InterviewCommonTable
            isLauncher={isLauncher}
            isPrincipal={isPrincipal}
            onJumpDetail={handleJumpDetail}
            condition={condition}
            sortOrders={sortOrders}
            loading={loading}
            onRefresh={handleRefresh}
            dataSource={dataSource}
            onChange={handleTableChange}
        ></InterviewCommonTable>
    );
    return (
        <>
            <Form layout="inline">
                <header className={styles.headerWrapper}>
                    <div className={styles.conditionWrapper}>
                        <Form.Item>
                            {form.getFieldDecorator('name', { initialValue: name })(
                                <CustomSearch
                                    onSearch={val => {
                                        if (!val && !query.name) return;
                                        handleSearch({ name: val });
                                    }}
                                    placeholder="搜索姓名、面试官"
                                />
                            )}
                        </Form.Item>
                        <a onClick={() => setAdvanceFold(val => !val)}>
                            高级搜索
                            <Icon type={advanceFold ? 'caret-down' : 'caret-up'} />
                        </a>
                        <Button type="primary" style={{ marginLeft: 12 }} onClick={() => handleSearch()}>
                            搜索
                        </Button>
                    </div>
                </header>
                {renderAdvanceCon()}
            </Form>
            {renderTable()}
            <Pagination
                current={pageNo}
                pageSize={pageSize}
                total={data?.data?.total}
                loading={loading}
                onChange={value => {
                    const { current, ...rest } = value;
                    setCondition({ ...rest, pageNo: current });
                }}
            />
        </>
    );
}

export default Form.create()(withRouter(InterviewList));
